﻿using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Threading;
using HslCommunication.Core.Net;
using HslCommunication.LogNet;

namespace HslCommunication.Enthernet
{
	/// <summary>
	/// 发布订阅类的客户端，使用指定的关键订阅相关的数据推送信息
	/// </summary>
	/// <remarks>
	/// 详细的使用说明，请参照博客<a href="http://www.cnblogs.com/dathlin/p/8992315.html">http://www.cnblogs.com/dathlin/p/8992315.html</a>
	/// </remarks>
	/// <example>
	/// 此处贴上了Demo项目的服务器配置的示例代码
	/// <code lang="cs" source="TestProject\HslCommunicationDemo\Hsl\FormPushNet.cs" region="FormPushNet" title="NetPushClient示例" />
	/// </example>
	// Token: 0x020000FB RID: 251
	public class NetPushClient : NetworkXBase
	{
		/// <summary>
		/// 实例化一个发布订阅类的客户端，需要指定ip地址，端口，及订阅关键字
		/// </summary>
		/// <param name="ipAddress">服务器的IP地址</param>
		/// <param name="port">服务器的端口号</param>
		/// <param name="key">订阅关键字</param>
		// Token: 0x06001515 RID: 5397 RVA: 0x0006D89C File Offset: 0x0006BA9C
		public NetPushClient(string ipAddress, int port, string key)
		{
			this.endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
			this.keyWord = key;
			bool flag = string.IsNullOrEmpty(key);
			if (flag)
			{
				throw new Exception(StringResources.Language.KeyIsNotAllowedNull);
			}
		}

		/// <summary>
		/// 创建数据推送服务
		/// </summary>
		/// <param name="pushCallBack">触发数据推送的委托</param>
		/// <returns>是否创建成功</returns>
		// Token: 0x06001516 RID: 5398 RVA: 0x0006D904 File Offset: 0x0006BB04
		public OperateResult CreatePush(Action<NetPushClient, string> pushCallBack)
		{
			this.action = pushCallBack;
			return this.CreatePush();
		}

		/// <summary>
		/// 创建数据推送服务，使用事件绑定的机制实现
		/// </summary>
		/// <returns>是否创建成功</returns>
		// Token: 0x06001517 RID: 5399 RVA: 0x0006D924 File Offset: 0x0006BB24
		public OperateResult CreatePush()
		{
			Socket coreSocket = this.CoreSocket;
			if (coreSocket != null)
			{
				coreSocket.Close();
			}
			OperateResult<Socket> operateResult = base.CreateSocketAndConnect(this.endPoint, 5000);
			bool flag = !operateResult.IsSuccess;
			OperateResult result;
			if (flag)
			{
				result = operateResult;
			}
			else
			{
				OperateResult operateResult2 = base.SendStringAndCheckReceive(operateResult.Content, 0, this.keyWord);
				bool flag2 = !operateResult2.IsSuccess;
				if (flag2)
				{
					result = operateResult2;
				}
				else
				{
					OperateResult<int, string> operateResult3 = base.ReceiveStringContentFromSocket(operateResult.Content, 30000);
					bool flag3 = !operateResult3.IsSuccess;
					if (flag3)
					{
						result = operateResult3;
					}
					else
					{
						bool flag4 = operateResult3.Content1 != 0;
						if (flag4)
						{
							Socket content = operateResult.Content;
							if (content != null)
							{
								content.Close();
							}
							result = new OperateResult(operateResult3.Content2);
						}
						else
						{
							AppSession appSession = new AppSession();
							this.CoreSocket = operateResult.Content;
							appSession.WorkSocket = operateResult.Content;
							try
							{
								appSession.WorkSocket.BeginReceive(new byte[0], 0, 0, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), appSession);
							}
							catch (Exception ex)
							{
								ILogNet logNet = base.LogNet;
								if (logNet != null)
								{
									logNet.WriteException(this.ToString(), StringResources.Language.SocketReceiveException, ex);
								}
								return new OperateResult(ex.Message);
							}
							this.closed = false;
							result = OperateResult.CreateSuccessResult();
						}
					}
				}
			}
			return result;
		}

		/// <summary>
		/// 关闭消息推送的界面
		/// </summary>
		// Token: 0x06001518 RID: 5400 RVA: 0x0006DA94 File Offset: 0x0006BC94
		public void ClosePush()
		{
			this.action = null;
			this.closed = true;
			bool flag = this.CoreSocket != null && this.CoreSocket.Connected;
			if (flag)
			{
				Socket coreSocket = this.CoreSocket;
				if (coreSocket != null)
				{
					coreSocket.Send(BitConverter.GetBytes(100));
				}
			}
			Thread.Sleep(20);
			Socket coreSocket2 = this.CoreSocket;
			if (coreSocket2 != null)
			{
				coreSocket2.Close();
			}
		}

		// Token: 0x06001519 RID: 5401 RVA: 0x0006DB00 File Offset: 0x0006BD00
		private void ReconnectServer(object obj)
		{
			for (;;)
			{
				bool flag = this.closed;
				if (flag)
				{
					break;
				}
				Console.WriteLine(StringResources.Language.ReConnectServerAfterTenSeconds);
				Thread.Sleep(this.reconnectTime);
				bool flag2 = this.closed;
				if (flag2)
				{
					break;
				}
				bool isSuccess = this.CreatePush().IsSuccess;
				if (isSuccess)
				{
					goto Block_3;
				}
			}
			return;
			Block_3:
			Console.WriteLine(StringResources.Language.ReConnectServerSuccess);
		}

		// Token: 0x0600151A RID: 5402 RVA: 0x0006DB6C File Offset: 0x0006BD6C
		[DebuggerStepThrough]
		private void ReceiveCallback(IAsyncResult ar)
		{
			NetPushClient.<ReceiveCallback>d__5 <ReceiveCallback>d__ = new NetPushClient.<ReceiveCallback>d__5();
			<ReceiveCallback>d__.<>t__builder = AsyncVoidMethodBuilder.Create();
			<ReceiveCallback>d__.<>4__this = this;
			<ReceiveCallback>d__.ar = ar;
			<ReceiveCallback>d__.<>1__state = -1;
			<ReceiveCallback>d__.<>t__builder.Start<NetPushClient.<ReceiveCallback>d__5>(ref <ReceiveCallback>d__);
		}

		/// <summary>
		/// 本客户端的关键字
		/// </summary>
		// Token: 0x170004FA RID: 1274
		// (get) Token: 0x0600151B RID: 5403 RVA: 0x0006DBAC File Offset: 0x0006BDAC
		public string KeyWord
		{
			get
			{
				return this.keyWord;
			}
		}

		/// <summary>
		/// 获取或设置重连服务器的间隔时间，单位：毫秒
		/// </summary>
		// Token: 0x170004FB RID: 1275
		// (get) Token: 0x0600151D RID: 5405 RVA: 0x0006DBBD File Offset: 0x0006BDBD
		// (set) Token: 0x0600151C RID: 5404 RVA: 0x0006DBB4 File Offset: 0x0006BDB4
		public int ReConnectTime
		{
			get
			{
				return this.reconnectTime;
			}
			set
			{
				this.reconnectTime = value;
			}
		}

		/// <summary>
		/// 当接收到数据的事件信息，接收到数据的时候触发。
		/// </summary>
		// Token: 0x1400002F RID: 47
		// (add) Token: 0x0600151E RID: 5406 RVA: 0x0006DBC8 File Offset: 0x0006BDC8
		// (remove) Token: 0x0600151F RID: 5407 RVA: 0x0006DC00 File Offset: 0x0006BE00
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public event Action<NetPushClient, string> OnReceived;

		/// <inheritdoc />
		// Token: 0x06001520 RID: 5408 RVA: 0x0006DC35 File Offset: 0x0006BE35
		public override string ToString()
		{
			return string.Format("NetPushClient[{0}]", this.endPoint);
		}

		// Token: 0x04000506 RID: 1286
		private readonly IPEndPoint endPoint;

		// Token: 0x04000507 RID: 1287
		private readonly string keyWord = string.Empty;

		// Token: 0x04000508 RID: 1288
		private Action<NetPushClient, string> action;

		// Token: 0x04000509 RID: 1289
		private int reconnectTime = 10000;

		// Token: 0x0400050A RID: 1290
		private bool closed = false;
	}
}
